#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, unicode_literals
import requests
from bs4 import BeautifulSoup

from logger import logger


class XinliFMApi(object):
    HOST_PREFIX_URL = 'http://fm.xinli001.com/'
    LATEST_LIST = HOST_PREFIX_URL + 'broadcast-pk-list'
    SINGLE_SONG = HOST_PREFIX_URL + 'broadcast?pk=%s'
    PAGE_LIST = HOST_PREFIX_URL + 'broadcast-list?p=%d&page=%d'

    def __init__(self):
        super(XinliFMApi, self).__init__()

    def get_latest_list(self):
        r = requests.get(XinliFMApi.LATEST_LIST)
        if r.status_code == 200:
            json_str = r.json()
            if json_str.get('code', -1) == 0:
                logger.debug(json_str)
                return json_str.get('data', [])

    def get_song_info(self, song_id):
        r = requests.get(XinliFMApi.SINGLE_SONG % song_id)
        if r.status_code == 200:
            json_str = r.json()
            if json_str.get('code', -1) == 0:
                return json_str.get('data', {})

    def get_next_list(self, index):
        results = []
        r = requests.get(XinliFMApi.PAGE_LIST % (index + 1, index + 1))
        if r.status_code == 200:
            soup = BeautifulSoup(r.text, 'html.parser')
            for a in soup.find_all("a", class_="broadcast broadcast_title"):
                results.append(a.attrs['data-pk'])
            return results


if __name__ == '__main__':
    api = XinliFMApi()
    latest_list = api.get_latest_list()
    print(latest_list)
    print(api.get_song_info(latest_list[0]))
    print(api.get_next_list(2))
